﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Data.Linq;
using System.Data.Common;
using TSV.Library.Common;
using TSV.Models;
using TSV.Models.Entities;

namespace TSV.Models
{
    public class PaymentDao : BaseDao
    {
        /// <summary>
        /// Insert a question without answer
        /// </summary>
        /// <param name="question"></param>
        /// <returns>int</returns>
        public int Insert(Payment payment)
        {
            int result = 0;
            try
            {
                if (payment != null)
                {
                    dbContext.Payments.InsertOnSubmit(payment);
                    //Submit changes to database
                    dbContext.SubmitChanges();
                    result = payment.ID;
                }
            }
            catch
            {
                result = 0;
            }
            return result;
        }

        public Message Insert(Payment objUI, List<Order> orderList)
        {
            Message msg = null;
            try
            {
                if (objUI != null)
                {
                    //insert and get it's id
                    int paymentId = Insert(objUI);
                    if (paymentId != 0)
                    {
                        List<PaymentDetail> paymentDetaiList = new List<PaymentDetail>();
                        foreach (Order item in orderList)
                        {
                            PaymentDetail detail = new PaymentDetail();
                            detail.ProductId = item.Id;
                            detail.PaymentID = paymentId;
                            detail.Price = item.Price;
                            detail.Quantity = item.Quantity;
                            detail.Subtotal = item.SubTotal;

                            paymentDetaiList.Add(detail);
                        }
                        dbContext.PaymentDetails.InsertAllOnSubmit(paymentDetaiList);
                        dbContext.SubmitChanges();
                    }

                    // Show success message
                    msg = new Message(MessageConstants.I0001, MessageType.Info, "Hóa đơn '" + objUI.Name + "'", "gửi");
                }
            }
            catch (Exception ex)
            {
                // Show system error
                msg = new Message(MessageConstants.E0007, MessageType.Error);
            }
            return msg;
        }
    }
}